<?php
class Shangku_RandomReviewsImport_Model_Import
{
	private $_ratingIds = null;
	private $_allStoreIds = null;
	Private $_defaultStoreId = null;
	
	public function importReviews($file)
	{
		if (is_file($file)){
			$parser = new Varien_Convert_Parser_Xml_Excel();
			$io = new Varien_Io_File();
			$xml = $io->read($file);
			$parser->setVar('single_sheet', 'Sheet 1');
			$parser->setData($xml);
			$parser->parse();
			$xmlData = $parser->getData();
			$feildNames = current($xmlData);
			while($row = next($xmlData)){
				$row = array_combine($feildNames, $row);
				if (
					!isset($row['category'])
					|| !isset($row['nickname'])
					|| !isset($row['title'])
					|| !isset($row['detail'])
					|| !isset($row['limit'])
					|| !isset($row['stores'])
				){
					throw new Exception("invalid content format!");
				}
				if (empty($row['stores']) || $row['stores'] == 0){
					$row['stores'] = $this->_getAllStoreIds();
				} else {
					$row['stores'] = explode('|', $row['stores']);
				}

				$this->_randomAddReview($row['category'], $row['nickname'], $row['title'], $row['detail'], $row['limit'], $row['stores']);
			}
		}
	}
	private function _getDefaultStoreId()
	{
		if(is_null($this->_defaultStoreId)){
			$defaultWebsite = Mage::getModel('core/website')->load(1, 'is_default');
			$this->_defaultStoreId = $defaultWebsite->getDefaultStore()->getId();
		}
		
		return $this->_defaultStoreId;
	}
	private function _getRatingIds()
	{
		if (is_null($this->_ratingIds)){
			$ratings = array();
			$ratingCollection = Mage::getModel('rating/rating')
				->getResourceCollection()
				->addEntityFilter('product')
				->setPositionOrder()
				->load();
			$this->_ratingIds = array_keys($ratingCollection->getItems());
		}
	
		return $this->_ratingIds;
	}
	
	private function _getRandomRatings(){
		$ratings = $this->_getRatingIds();
		foreach($ratings as $ratingId){
			$ratings[$ratingId] = mt_rand($ratingId * 5 - 1, $ratingId * 5);
		}
	
		return $ratings;
	}
	
	private function _getRandomProductIds($categoryId, $limit = 5)
	{
		$category = Mage::getModel('catalog/category')->load($categoryId);
		$productCollection = Mage::getModel('catalog/product')->getCollection()
			->addCategoryFilter($category)
			->setCurPage(1)
			->setPageSize($limit)
			->addOrder(new Zend_Db_Expr('RAND()'));
	
		$productIds = array();
		foreach($productCollection->getData() as $product){
			$productIds[] = $product['entity_id'];
		}
	
		return $productIds;
	}
	
	private function _getRandomCurMonthDateTime()
	{
		#$startTime = mktime(0, 0, 0, date('n'), 1, date('Y'));
		#$endTime = mktime(23, 59, 59, date('n'), date('t'), date('Y'));
		$startTime = time()-30*24*3600;
		$endTime = time();
		$randomTime = mt_rand($startTime, $endTime);
	
		return date('Y-m-d H:i:s', $randomTime);
	}
	
	private function _randomAddReview($categoryId, $nickName, $title, $review, $limit=5, $stores =1)
	{
		$productIds = $this->_getRandomProductIds($categoryId, $limit);
	
		if (!$productIds){
			return false;
		}
		$data = array(
			'nickname' => $nickName,
			'title' => $title,
			'detail' => $review
		);
		$defaultStoreId = $this->_getDefaultStoreId();
		foreach($productIds as $productId){
			$rating = $this->_getRandomRatings();
			$review     = Mage::getModel('review/review')->setData($data);
			$validate = $review->validate();
			if ($validate === true) {
				$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE))
					->setEntityPkValue($productId)
					->setStatusId(Mage_Review_Model_Review::STATUS_APPROVED)
					->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())
					->setStoreId($defaultStoreId)
					->setStores((array)$stores)
					->save();
					
				$review->setCreatedAt($this->_getRandomCurMonthDateTime())->save();
					
				foreach ($rating as $ratingId => $optionId) {
					Mage::getModel('rating/rating')
						->setRatingId($ratingId)
						->setReviewId($review->getId())
						->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())
						->addOptionVote($optionId, $productId);
				}
					
				$review->aggregate();
				
			}
		}
	}
	private function _getAllStoreIds()
	{
		if(is_null($this->_allStoreIds)){
			$this->_allStoreIds = array_keys(Mage::getModel('core/store')->getCollection()->toOptionHash());
		}
	
		return $this->_allStoreIds;
	}
}
